﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.customs;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.middle;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BenCaoXuan.Api.Admin.Controllers.middle
{
    [ApiGroup("Middle(移动端模块)")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MiddleController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly I_MiddleLogin_Service _middleLogin_Service;

        public MiddleController(IConfiguration configuration,I_MiddleLogin_Service middleLogin_Service)
        {
            _configuration = configuration;
            _middleLogin_Service = middleLogin_Service;
        }

        /// <summary>
        /// 获取当前登录移动端的用户
        /// </summary>
        /// <returns></returns>
        private Customs_Dto Get_Middle_User()
        {
            var code = Response.HttpContext.User.Identity?.Name;

            return _middleLogin_Service.Check_Middle_Login(code!, "");
        }
        /// <summary>
        /// 初始化员工密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Init_User()
        {
            var result = await _middleLogin_Service.Init_User();
            return Ok(result);
        }

        /// <summary>
        /// 移动端-登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Logins(Login_Dto dto) {
            dto.code = Config.GUID2();
            var data = await _middleLogin_Service.Logins(dto);
            if (data.code == Api_Code.ok)
            {
                var claims = new[]
                    {
                    new Claim(ClaimTypes.Name,  dto.code),
                    new Claim(ClaimTypes.Actor,  dto.account!),
                    new Claim(ClaimTypes.Role,"middle")//角色设定
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 12), //token 过期时间
                    signingCredentials: creds);
                
                data.data = new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                };

            }

            return Ok(data);
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "middle")]
        public IActionResult Check_login() 
        {
            var user = this.Get_Middle_User();
            if (user == null)
            {
                return Unauthorized();//401
            }
            return Ok(new Api_Result_Dto()
            {
                code = 0,
                message = "ok",
                data = new
                {
                    id=user.id,
                    name = user.name,
                    account = user.account,
                    isConvert=user.isConvert
                }
            });
        }

        /// <summary>
        /// 移动端-退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "middle")] 
        public async Task<IActionResult> Logout()
        {
            try
            {
                // 从JWT令牌中获取用户账号
                var account = User.FindFirstValue(ClaimTypes.Actor);
                if (string.IsNullOrEmpty(account))
                {
                    return Ok(-1);
                }

                // 调用服务层处理退出逻辑
                var result = await _middleLogin_Service.Logout(account);

                return Ok(result);
            }
            catch (Exception ex)
            {
                return Ok(-1);
            }
        }
    }
}
